<route lang="json5" type="page">
{
  style: {
    navigationBarTitleText: '登录',
  },
}
</route>

<template>
  <view class="flex flex-col items-center justify-start px-4 py-8 full-screen-120px bg-gray-50">
    <!-- 顶部标题 -->
    <view class="w-full text-left mb-8">
      <text class="text-2xl font-bold text-gray-800">手机号登录</text>
    </view>

    <!-- 登录方式切换 -->
    <view class="w-full flex mb-8 border-b border-gray-200">
      <view
        v-for="tab in tabs"
        :key="tab.key"
        class="relative flex-1 text-center py-3"
        @tap="(activeTab = tab), (activeTabKey = tab.key)"
      >
        <text
          :class="[
            'text-base',
            activeTabKey === tab.key ? 'text-blue-500 font-medium' : 'text-gray-600',
          ]"
        >
          {{ tab.name }}
        </text>
        <!-- 活动标签下的蓝线 -->
        <view
          v-if="activeTabKey === tab.key"
          class="absolute bottom-0 left-0 w-full h-0.5 bg-blue-500"
        />
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="w-full space-y-6">
      <!-- 手机号输入 -->
      <view class="relative">
        <input
          type="number"
          v-model="phone"
          placeholder="请输入手机号"
          class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 outline-none"
        />
      </view>

      <!-- 密码登录 -->
      <template v-if="activeTabKey === 'password'">
        <view class="relative">
          <input
            :type="showPassword ? 'text' : 'password'"
            v-model="password"
            placeholder="请输入密码"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 outline-none"
          />
          <text
            class="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-500"
            @tap="showPassword = !showPassword"
          >
            {{ showPassword ? '隐藏' : '显示' }}
          </text>
        </view>
      </template>

      <!-- 验证码登录 -->
      <template v-else>
        <view class="relative flex space-x-4">
          <input
            type="number"
            v-model="verifyCode"
            placeholder="请输入验证码"
            class="flex-1 px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 outline-none"
          />
          <button
            @tap="handleSendCode"
            :disabled="!isPhoneValid || countdown > 0 || throttleBtnEnabled"
            class="w-32 py-3 rounded-lg bg-blue-500 text-white font-medium disabled:opacity-50 disabled:cursor-not-allowed h-10 line-height-none"
          >
            {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
          </button>
        </view>
        <view class="text-gray text-center">首次使用的手机号将会自动注册</view>
      </template>

      <!-- 登录按钮 -->
      <button
        @click="handleLogin"
        :disabled="!isValid || throttleBtnEnabled"
        class="w-full py-3 rounded-lg bg-blue-500 text-white font-medium disabled:opacity-50 disabled:cursor-not-allowed"
      >
        {{ activeTab.loginBtnText }}
      </button>

      <!-- 底部链接 -->
      <view class="flex justify-between items-center mt-4">
        <navigator url="/pages/me/login/forgot-pwd" class="text-blue-500">忘记密码</navigator>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { passwordLogin, smsLoginApi, smsLoginSendCodeApi } from '@/service/me/login/authApi'
import { useUserStore } from '@/store'
import { ref, computed } from 'vue'

// 按钮节流
const throttleBtnEnabled = ref<boolean>(false)
function throttleBtn(wait: number = 1111): boolean {
  if (throttleBtnEnabled.value) {
    return false
  }
  throttleBtnEnabled.value = true
  setTimeout(() => {
    throttleBtnEnabled.value = false
  }, wait)
  return true
}

// 标签页配置
const tabs = [
  { key: 'verify', name: '验证码登录', loginBtnText: '登录/注册' },
  { key: 'password', name: '密码登录', loginBtnText: '登录' },
]
const activeTab = ref(tabs[0])
const activeTabKey = ref(activeTab.value.key)

// 表单数据
const phone = ref('15088123456')
const password = ref('123456')
const verifyCode = ref('123456')
const showPassword = ref(false)
const countdown = ref(0)

// 手机号验证
const isPhoneValid = computed(() => {
  const phoneReg = /^1[3-9]\d{9}$/
  return phoneReg.test(phone.value)
})

// 表单验证
const isValid = computed(() => {
  if (!isPhoneValid.value) return false

  if (activeTabKey.value === 'password') {
    return password.value.length >= 6
  } else {
    return verifyCode.value.length === 6
  }
})

// 发送验证码
const handleSendCode = async () => {
  if (!isPhoneValid.value || !throttleBtn()) return
  // 开始倒计时
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)

  // 实现发送验证码逻辑
  await smsLoginSendCodeApi(phone.value)
  uni.showToast({
    title: '验证码已发送',
    icon: 'success',
  })
}

// 登录处理
const handleLogin = async function () {
  if (!isValid.value || !throttleBtn()) return

  uni.showLoading({
    title: '登录中...',
  })

  // 根据不同登录方式处理登录逻辑
  const loginType = activeTabKey.value
  const userStore = useUserStore()
  let apiResult = null
  if (loginType === tabs[0].key) {
    apiResult = await smsLoginApi(phone.value, verifyCode.value)
  } else if (loginType === tabs[1].key) {
    apiResult = await passwordLogin(phone.value, password.value)
  }

  uni.hideLoading()
  uni.showToast({
    title: apiResult.msg,
    icon: 'success',
  })
  const userInfo = apiResult.data as unknown as IUserInfo
  userStore.setUserInfo(userInfo)
  setTimeout(() => {
    uni.switchTab({ url: '/pages/me/me' })
  }, 1000)
}
</script>

<style lang="scss" scoped>
// 空样式，全部复用 UnoCSS
</style>
